
import store from '../store'
import conf from '../config/config'
import code from '../config/code'

export default class Request {
  request({ url, data = {}, method = 'POST' }) {
    return new Promise((resolve, reject) => {


      // 本地调试H5
      let request_url = `${conf.baseUrl}${url}`

      if (conf.dev) {
        request_url = request_url.replace('/api', '/supplier')
      }

      uni.request({
        url: request_url,
        data,
        method,
        // sslVerify: false,
        header: {
          'content-type': 'application/json;charset=utf8mb4',
          [conf.token_name]: store.getters['User/token'] || ''
        },
        success: response => {
          const { data } = response
          if (data.code === code.CODE_SUCCESS) {
            resolve(data)
          } else if (data.code === code.CODE_TOKEN_EXPIRED) {
            // 未登录
            uni.showToast({
              title: '您还没有登录,请登录!',
              icon: 'none',
              duration: 1000
            })
            setTimeout(() => {
              uni.navigateTo({
                // url: '/sub_common/user/login'
                url: '/pages/bfc/login'
              })
            }, 500)
          } else {
            if (data.code === code.CODE_ERROR) {
              uni.showToast({
                title: data.message,
                icon: 'none',
                duration: 1000
              })
              reject(data.message)
            } else {
              reject(data.message)
            }
          }
        }
      })

    })
  }

  // 测试
  test() {
    return this.request({
      url: '/site/test',
      data: { title: '123', age: 'abc' },
      method: 'POST'
    })
  }
}
